//
//  PicturePickVC.swift
//  测试-图片选择器
//
//  Created by shmily on 15/8/8.
//  Copyright © 2015年 shmilyAshen. All rights reserved.
//

import UIKit

///cell 的可重用 ID
private let kPicturePickID = "kPicturePickID"

/// 图片选择器控件(collectionViewController)
class PicturePickVC: UICollectionViewController,PicturePickCellDelegate {
   
    /// 图片数组,保存图片
    private lazy var images: [UIImage] = [UIImage]()
    /// 最大图像数量
    private let kMaxPictures = 9
    /// 记录当前选择 cell 的索引
    private var currentIndex = 0
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        //设置 flowLayout
        prepareFlowLayout()
        // 注册 cell
        collectionView?.registerClass(PicturePickCell.self, forCellWithReuseIdentifier: kPicturePickID)
    }
    
    /// 准备 flowLayout
    func prepareFlowLayout() {
        let flowLayout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 10
        flowLayout.itemSize = CGSize(width: 80, height: 80)
        flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10)
        flowLayout.collectionView?.pagingEnabled = true
        
        collectionView?.backgroundColor = UIColor.darkGrayColor()
    }
    //添加按钮
    func PicturePickCellAddImage(cell: PicturePickCell) {
        let picturePC = UIImagePickerController()
        picturePC.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        picturePC.delegate = self
        
        let indextpath = collectionView?.indexPathForCell(cell)
        currentIndex = indextpath!.item
        
        presentViewController(picturePC, animated: true, completion: nil)
    }
    //删除按钮
    func PicturePickCellDeleteImage(cell: PicturePickCell) {
        images.removeAtIndex(currentIndex)
        collectionView?.reloadData()
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kPicturePickID, forIndexPath: indexPath) as! PicturePickCell
        /// 设置cell 相关属性
        cell.delegate = self
        cell.image = (indexPath.item == images.count) ? nil : images[indexPath.item]

        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 超过8张,不显示加号按钮
        return  (images.count == kMaxPictures) ? images.count : (images.count + 1)
    }
    
    //MARK:- 初始化构造函数
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - 实现代理方法
extension PicturePickVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //添加图像
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        let img = image.scaleImage(300)
        
        print("currentIndex = \(currentIndex)")
        print("images.count = \(images.count)")
        if currentIndex == images.count { // 点击的是最后一个按钮
            images.append(img) //追加图片
        } else {
            images[currentIndex] = img //覆盖图像
        }
        
        collectionView?.reloadData() // 刷新数据
        dismissViewControllerAnimated(true, completion: nil) // 关闭控制器
    }
}
/// 按钮事件的代理方法
protocol PicturePickCellDelegate: NSObjectProtocol {
    /// 单击添加图片按钮
    func PicturePickCellAddImage(cell: PicturePickCell)
    /// 单击删除图片按钮
    func PicturePickCellDeleteImage(cell: PicturePickCell)
}

/// 图片选择器 cell
class PicturePickCell: UICollectionViewCell {
     /// 图片属性
    var image: UIImage? {
        didSet{
            if image != nil {
                btnPhoto.setImage(image, forState: UIControlState.Normal)
            } else {
                btnPhoto.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                btnPhoto.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
            }
            btnDelete.hidden = (image == nil)
        }
    }

    /// 代理属性
    weak var delegate: PicturePickCellDelegate?
    
    // 删除图像
    @objc private func deleteImage() {
        delegate?.PicturePickCellDeleteImage(self)
    }
    //添加按钮点击事件
    func addPictureClick() {  // 需要使用代理方法,因为要修改 images
        delegate?.PicturePickCellAddImage(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(btnPhoto)
        contentView.addSubview(btnDelete)
        btnDelete.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=0)-[btn]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["btn": btnDelete]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[btn]-(>=0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["btn": btnDelete]))
        backgroundColor = UIColor.blueColor()
        
        btnPhoto.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[imgView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imgView":btnPhoto]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[imgView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["imgView":btnPhoto]))
        btnPhoto.backgroundColor = UIColor.grayColor()
        btnPhoto.addTarget(self, action: "addPictureClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    //MARK:- 懒加载视图
    //删除按钮
    private lazy var btnDelete: UIButton = {
        let btn = UIButton()
         btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
         btn.addTarget(self, action: "deleteImage", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()

    // 显示图片按钮
    private lazy var btnPhoto: UIButton = UIButton()
}